package com.bzyd.mp.datascope;

import cn.hutool.core.collection.CollUtil;
import com.bzyd.mp.datascope.strategy.DataScopeStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据权限策略工厂
 */
@Slf4j
@Component
public class DataScopeStrategyFactory implements ApplicationContextAware {

    private final Map<String, DataScopeStrategy> dataScopeStrategyMap = new HashMap<>();

    /**
     * 获取数据权限策略
     */
    public DataScopeStrategy getDataScopeStrategy(String mode) {
        return dataScopeStrategyMap.get(mode);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, DataScopeStrategy> beansOfType = applicationContext.getBeansOfType(DataScopeStrategy.class);
        if (CollUtil.isNotEmpty(beansOfType)) {
            for (DataScopeStrategy dataScopeStrategy : beansOfType.values()) {
                dataScopeStrategyMap.put(dataScopeStrategy.mode(), dataScopeStrategy);
            }
        }
    }
}
